package oop.controller.action.answer;

import java.sql.SQLException;

import oop.controller.action.DefaultAction;
import oop.data.Answer;
import oop.data.BaseQuestion;
import oop.db.dao.AnswerDAO;
import oop.db.dao.QuestionAnswerDAO;
import oop.db.dao.QuestionDAO;

import com.mysql.jdbc.StringUtils;
import com.oreilly.servlet.ParameterNotFoundException;

public class CreateAction extends DefaultAction {

	@Override
	public void performImpl() throws SQLException {
		long questionId;
		try {
			questionId = getParams().getLong("question");
		} catch (NumberFormatException e) {
			error("Mã câu hỏi không hợp lệ.");
			return;
		} catch (ParameterNotFoundException e) {
			error("Bạn cần chọn câu hỏi.");
			return;
		}
		BaseQuestion question = QuestionDAO.fetchByIdBase(questionId);

		title("Tạo câu trả lời mới");
		request.setAttribute("question", question);

		String submit = request.getParameter("submit");
		if ("create".equals(submit)) {
			// int priority = parser.getIntParameter("priority");

			String content;
			try {
				content = getParams().getString("content");
			} catch (ParameterNotFoundException e) {
				contentError = "Bạn cần nhập nội dung phương án trả lời.";
				return;
			}

			boolean correct = !StringUtils.isNullOrEmpty(request
					.getParameter("correct"));

			Answer answer = AnswerDAO.create(content, 1, getUser().getId());
			QuestionAnswerDAO.addAnswer(questionId, answer.getId(), correct);

			boolean more = getParams().hasParameter("more");
			if (more) {
				setNextAction("answer.create&questioin=" + questionId
						+ "&content=&correct=&submit=");
			} else {
				setNextAction("question.view&qv_id=" + questionId);
			}
		}
	}

	private String contentError;

	public String getContentError() {
		return contentError;
	}

}
